package com.ruoyi;
import com.coupang.openapi.sdk.Hmac;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * Coupang 获取分类列表测试类
 */
public class CategoryList {

    private static final String HOST = "api-gateway.coupang.com";
    private static final int PORT = 443;
    private static final String SCHEMA = "https";
    
    //replace with your own accessKey
    private static final String ACCESS_KEY = "fe8a5ff1-28be-4a36-8694-577cc7960166";
    //replace with your own secretKey
    private static final String SECRET_KEY = "f05224e25ebb0c237564da5cce5be106926c7930";

    public void getCategories() {
        //params
        String method = "GET";
        String vendorId = "A158000DM0";
        // 获取品类列表 API 路径（根据官方文档）
        // 参考：https://developers.coupangcorp.com/hc/zh-cn/articles/360033400814-查看品类列表
        // 正确的路径：https://api-gateway.coupang.com/v2/providers/seller_api/apis/api/v1/marketplace/meta/display-categories
        String path = "/v2/providers/seller_api/apis/api/v1/marketplace/meta/display-categories";

        CloseableHttpClient client = null;
        try {
            //create client
            client = HttpClients.createDefault();
            
            /********************************************************/
            //authorize, demonstrate how to generate hmac signature here
            String authorization = Hmac.generate(method, path, SECRET_KEY, ACCESS_KEY);
            System.out.println("Authorization: " + authorization);
            System.out.println("Method: " + method);
            System.out.println("Path: " + path);
            /********************************************************/

            //build uri
            URIBuilder uriBuilder = new URIBuilder()
                    .setScheme(SCHEMA)
                    .setHost(HOST)
                    .setPort(PORT)
                    .setPath(path);
            
            HttpGet requestGet = new HttpGet(uriBuilder.build().toString());

            /********************************************************/
            // set headers
            requestGet.addHeader("Authorization", authorization);
            requestGet.addHeader("X-Requested-By", vendorId);
            requestGet.addHeader("X-MARKET", "KR");
            /********************************************************/
            requestGet.addHeader("Content-Type", "application/json");
            
            System.out.println("\n请求头信息:");
            System.out.println("X-Requested-By: " + vendorId);
            System.out.println("X-MARKET: KR");
            System.out.println("请求 URL: " + uriBuilder.build().toString());
            
            CloseableHttpResponse response = null;
            try {
                //execute get request
                System.out.println("\n发送获取分类列表请求...");
                response = client.execute(requestGet);
                //print result
                System.out.println("\n=== 响应结果 ===");
                System.out.println("status code: " + response.getStatusLine().getStatusCode());
                System.out.println("status message: " + response.getStatusLine().getReasonPhrase());
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                System.out.println("result: " + result);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (response != null) {
                    try {
                        response.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void tryAllPaths() {
        String vendorId = "A158000DM0";
        String[] possiblePaths = {
            "/v2/providers/seller_api/apis/api/v1/marketplace/meta/display-categories",
            "/v2/providers/openapi/apis/api/v4/vendors/" + vendorId + "/meta/display-category-codes",
            "/v2/providers/seller_api/apis/api/v4/vendors/" + vendorId + "/meta/display-category-codes",
            "/v2/providers/openapi/apis/api/v4/meta/display-category-codes",
            "/v2/providers/seller_api/apis/api/v4/meta/display-category-codes"
        };
        
        for (int i = 0; i < possiblePaths.length; i++) {
            System.out.println("\n========================================");
            System.out.println("尝试路径 " + (i + 1) + ": " + possiblePaths[i]);
            System.out.println("========================================");
            testPath(possiblePaths[i]);
        }
    }
    
    private void testPath(String path) {
        String method = "GET";
        String vendorId = "A158000DM0";
        
        CloseableHttpClient client = null;
        try {
            client = HttpClients.createDefault();
            String authorization = Hmac.generate(method, path, SECRET_KEY, ACCESS_KEY);
            
            URIBuilder uriBuilder = new URIBuilder()
                    .setScheme(SCHEMA)
                    .setHost(HOST)
                    .setPort(PORT)
                    .setPath(path);
            
            HttpGet requestGet = new HttpGet(uriBuilder.build().toString());
            requestGet.addHeader("Authorization", authorization);
            requestGet.addHeader("X-Requested-By", vendorId);
            requestGet.addHeader("X-MARKET", "KR");
            requestGet.addHeader("Content-Type", "application/json");
            
            CloseableHttpResponse response = null;
            try {
                response = client.execute(requestGet);
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("状态码: " + statusCode);
                
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();
                    String result = EntityUtils.toString(entity);
                    System.out.println("✅ 成功！结果: " + result);
                } else {
                    System.out.println("❌ 失败: " + response.getStatusLine().getReasonPhrase());
                }
            } catch (Exception e) {
                System.out.println("❌ 请求异常: " + e.getMessage());
            } finally {
                if (response != null) {
                    try {
                        response.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("❌ 错误: " + e.getMessage());
        } finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        System.out.println("========================================");
        System.out.println("Coupang 获取分类列表 API 测试");
        System.out.println("========================================\n");
        
        CategoryList categoryList = new CategoryList();
        
        // 先尝试标准路径
        System.out.println("【方式1】尝试标准路径:");
        categoryList.getCategories();
        
        System.out.println("\n\n【方式2】尝试所有可能的路径:");
        System.out.println("（如果上面失败，会尝试多个路径找到正确的）");
        categoryList.tryAllPaths();
        
        System.out.println("\n========================================");
        System.out.println("测试完成");
        System.out.println("========================================");
        
        System.out.println("\n提示：");
        System.out.println("如果所有 API 都不可用，您需要：");
        System.out.println("1. 登录 Coupang Wing 卖家后台");
        System.out.println("2. 在商品管理中查看您有权限使用的分类");
        System.out.println("3. 或者联系 Coupang 客服获取可用的 displayCategoryCode");
        System.out.println("   邮箱: openapisupport@coupang.com");
        System.out.println("   电话: +82-1600-9879");
    }
}

